from flask import Flask, jsonify, request
from flask_sqlalchemy import SQLAlchemy
from flask_cors import CORS
import pymysql

app = Flask(__name__)
CORS(app)  # 允许跨域请求

# 数据库配置 - 使用你提供的root用户和密码
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:1231@localhost/todo_db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)


# 任务模型
class Task(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100), nullable=False)
    completed = db.Column(db.Boolean, default=False)

    def to_dict(self):
        return {
            'id': self.id,
            'title': self.title,
            'completed': self.completed
        }


# 自动创建数据库和表
def initialize_database():
    try:
        # 先连接MySQL服务器（不带数据库名）
        connection = pymysql.connect(
            host='localhost',
            user='root',
            password='1231',
            charset='utf8mb4'
        )

        with connection.cursor() as cursor:
            # 创建数据库（如果不存在）
            cursor.execute("CREATE DATABASE IF NOT EXISTS todo_db CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci")
            connection.commit()

        # 现在连接新创建的数据库
        connection.select_db('todo_db')
        with connection.cursor() as cursor:
            # 创建表（如果不存在）
            cursor.execute("""
                           CREATE TABLE IF NOT EXISTS task
                           (
                               id        INT AUTO_INCREMENT PRIMARY KEY,
                               title     VARCHAR(100) NOT NULL,
                               completed BOOLEAN DEFAULT FALSE
                           ) ENGINE = InnoDB
                             DEFAULT CHARSET = utf8mb4
                           """)
            connection.commit()

    except Exception as e:
        print(f"数据库初始化失败: {e}")
    finally:
        if connection:
            connection.close()


# 使用应用上下文初始化数据库
with app.app_context():
    initialize_database()
    db.create_all()  # 创建所有表


# API路由
@app.route('/tasks', methods=['GET'])
def get_tasks():
    tasks = Task.query.all()
    return jsonify([task.to_dict() for task in tasks])


@app.route('/tasks', methods=['POST'])
def add_task():
    data = request.get_json()
    if not data or 'title' not in data:
        return jsonify({'error': '任务标题不能为空'}), 400

    new_task = Task(title=data['title'])
    db.session.add(new_task)
    db.session.commit()
    return jsonify(new_task.to_dict()), 201


@app.route('/tasks/<int:id>', methods=['PUT'])
def update_task(id):
    task = Task.query.get_or_404(id)
    data = request.get_json()

    if 'title' in data:
        task.title = data['title']
    if 'completed' in data:
        task.completed = data['completed']

    db.session.commit()
    return jsonify(task.to_dict())


@app.route('/tasks/<int:id>', methods=['DELETE'])
def delete_task(id):
    task = Task.query.get_or_404(id)
    db.session.delete(task)
    db.session.commit()
    return '', 204


if __name__ == '__main__':
    app.run(debug=True, port=5000)